import React from 'react';
import { useEffect, useState } from 'react';
import { hotApi } from '../../services/hotApi';
import { useAsync } from '../../hooks';
import { useThemeStore } from '../../stores/themeStore';
import { getTheme } from '../../theme/config';
import CustomCard from '../custom/CustomCard';
import CustomButton from '../custom/CustomButton';
import CustomSelect from '../custom/CustomSelect';
import CustomTag from '../custom/CustomTag';
import CustomSpin from '../custom/CustomSpin';
import CustomAlert from '../custom/CustomAlert';
import AnimatedList from '../ui/AnimatedList';
import '../../components/custom/customStyles.css';

interface HotItem {
  index: number;
  title: string;
  url: string;
  hot?: string | number;
  desc?: string;
  pic?: string;
}

interface HotData {
  platform: string;
  subtitle: string;
  update_time: string;
  data: HotItem[];
}

interface Platform {
  name: string;
  platform_name: string;
}

const HotDataContent: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [selectedPlatform, setSelectedPlatform] = useState<string>('zhihu');
  const [hotData, setHotData] = useState<Record<string, HotData>>({});
  
  const {
    data: platforms,
    loading: platformsLoading,
    execute: fetchPlatforms
  } = useAsync(hotApi.getPlatforms, true);

  const {
    loading: dataLoading,
    error: dataError,
    execute: fetchData
  } = useAsync(hotApi.getPlatformData);

  const {
    loading: refreshLoading,
    execute: refreshData
  } = useAsync(hotApi.refreshPlatformCache);

  // 获取选定平台的数据
  useEffect(() => {
    if (selectedPlatform) {
      fetchData(selectedPlatform, 30).then(data => {
        setHotData(prev => ({ ...prev, [selectedPlatform]: data }));
      }).catch(error => {
        console.error('获取热点数据失败:', error);
      });
    }
  }, [selectedPlatform]);

  const handleRefresh = async () => {
    try {
      await refreshData(selectedPlatform);
      // 刷新后重新获取数据
      const data = await fetchData(selectedPlatform, 30);
      setHotData(prev => ({ ...prev, [selectedPlatform]: data }));
    } catch (error) {
      console.error('刷新数据失败:', error);
    }
  };

  const handlePlatformChange = (platform: string) => {
    setSelectedPlatform(platform);
  };

  // 将热点数据转换为 AnimatedList 项目
  const convertToAnimatedListItems = (data: HotItem[]) => {
    return data.map((item, index) => ({
      id: item.index || index + 1,
      content: (
        <div className="hot-item-container">
          <div 
            className="hot-item-index"
            style={{ 
              backgroundColor: index < 3 ? '#ff4d4f' : theme.glowColor,
              color: 'white',
            }}
          >
            {item.index || index + 1}
          </div>
          
          <div className="hot-item-content">
            <div className="hot-item-title-row">
              <a 
                href={item.url} 
                target="_blank" 
                rel="noopener noreferrer"
                className="hot-item-title-link"
                style={{ 
                  color: theme.glowColor,
                }}
              >
                {item.title}
              </a>
              {item.hot && (
                <CustomTag color="volcano">
                  {typeof item.hot === 'number' ? item.hot.toLocaleString() : item.hot}
                </CustomTag>
              )}
            </div>
            {item.desc && (
              <div 
                className="hot-item-description"
                style={{ color: theme.textSecondary }}
              >
                {item.desc}
              </div>
            )}
          </div>
          
          {item.pic && (
            <img 
              src={item.pic} 
              alt={item.title}
              className="hot-item-image"
              style={{ 
                border: `1px solid ${theme.borderColor}`
              }}
              onError={(e) => {
                (e.target as HTMLImageElement).style.display = 'none';
              }}
            />
          )}
        </div>
      )
    }));
  };

  const currentData = hotData[selectedPlatform];
  
  const platformOptions = platforms?.platforms.map((platform: Platform) => ({
    value: platform.name,
    label: platform.platform_name,
  })) || [];

  return (
    <div 
      style={{ 
        padding: '24px', 
        minHeight: '100vh', 
        backgroundColor: theme.contentBackground,
        color: theme.textPrimary
      }}
    >
      <div style={{ marginBottom: '16px' }}>
        <CustomCard>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <h2 style={{ 
              margin: 0, 
              display: 'flex', 
              alignItems: 'center',
              color: theme.textPrimary,
              fontSize: '24px',
              fontWeight: 600
            }}>
              <span style={{ color: '#ff4d4f', marginRight: 8 }}>🔥</span>
              实时热点数据
            </h2>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              <CustomSelect
                value={selectedPlatform}
                onChange={handlePlatformChange}
                options={platformOptions}
                loading={platformsLoading}
                placeholder="选择平台"
              />
              <CustomButton 
                type="primary"
                onClick={handleRefresh}
                loading={refreshLoading}
              >
                刷新数据
              </CustomButton>
            </div>
          </div>
          
          {currentData && (
            <div style={{ marginBottom: 16, color: theme.textSecondary }}>
              {currentData.subtitle} • 更新时间: {new Date(currentData.update_time).toLocaleString()}
            </div>
          )}
        </CustomCard>
      </div>

      <div>
        {dataLoading ? (
          <CustomCard>
            <div className="hot-loading-container">
              <CustomSpin size="large" />
              <div 
                className="hot-loading-text"
                style={{ color: theme.textPrimary }}
              >
                正在加载热点数据...
              </div>
            </div>
          </CustomCard>
        ) : dataError ? (
          <CustomAlert
            message="获取数据失败"
            description={dataError}
            type="error"
            action={
              <CustomButton 
                type="danger"
                onClick={() => fetchData(selectedPlatform, 30)}
              >
                重试
              </CustomButton>
            }
          />
        ) : currentData ? (
          <CustomCard 
            style={{
              background: theme.cardBackground,
              backdropFilter: mode === 'dark' ? 'blur(25px)' : 'blur(15px)',
              border: `1px solid ${theme.cardBorder}`
            }}
          >
            <AnimatedList
              items={convertToAnimatedListItems(currentData.data)}
              maxHeight={600}
              showGradients={true}
              containerWidth="100%"
            />
          </CustomCard>
        ) : (
          <CustomCard>
            <div 
              className="hot-empty-state"
              style={{ color: theme.textSecondary }}
            >
              请选择一个平台查看热点数据
            </div>
          </CustomCard>
        )}
      </div>
    </div>
  );
};

export default HotDataContent;